package com.bwie.common.exceptionhandler;

import com.bwie.common.result.Result;
import lombok.extern.log4j.Log4j2;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.security.auth.login.LoginException;

@RestControllerAdvice
@Log4j2
public class GlobalException {

    @ExceptionHandler(LoginException.class)
    public Result loginException(LoginException loginException){
        String message = loginException.getMessage();
        log.error("错误信息为：{}",message);
        return Result.error(message);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidException(MethodArgumentNotValidException methodArgumentNotValidException){
        //获取所有异常消息
        BindingResult bindingResult = methodArgumentNotValidException.getBindingResult();
        StringBuffer sb = new StringBuffer();
        //循环
        bindingResult.getAllErrors().forEach(error->{

            sb.append(error.getDefaultMessage());
            log.error("错误信息为:{}",sb.toString());
        });
        return Result.error(sb.toString());
    }
}
